<template>
  <div class="equipment-overview">
    <div class="equipment-overview-box">
      <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
    </div>
    <div class="equipment-overview-box mt-[16px]">
      <!-- <div class="sj-text-title text-[18px]">概览统计(个)</div> -->
      <div class="flex-c mt-[16px]">
        <div v-for="(item, key) in headerTitle" :key="key" class="p-[16px] flex cursor-pointer flex-1"
          @click="goDevice(item)">
          <img :src="getAssetURL(`/src/assets/images/equipment-overview/${key}.png`)"
            class="w-[42px] h-[42px] mr-[10px] " />
          <div>
            <div class="!font-[D-DIN] !text-[22px]">
              <ReNormalCountTo :endVal="deviceOverviewData ? deviceOverviewData[key] : 0"
                :duration="Math.random() * 1000 + 1000" />
            </div>
            <el-text class="sj-text-secondary-title">
              {{ isNullOrEmpty(item.name) }}
            </el-text>
          </div>
        </div>
      </div>
    </div>
    <div class="equipment-overview-box mt-[16px]">
      <!-- <div class="sj-text-title text-[18px]">各项目情况</div> -->
      <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)"
        showOverflowTooltip border:isShowPag="false">
        <template #deviceSN="{ row }">
          <!-- <div class="cursor-pointer" @click="showDeviceInfo(row)"> -->
          <div>
            {{ isNullOrEmpty(row?.deviceSN || '--') }}
          </div>
        </template>
        <template #commStatus="{ row }">
          <el-tag :type="DEVICESTATUSTABLE[row?.commStatus]?.type">
            {{ isNullOrEmpty(DEVICESTATUSTABLE[row?.commStatus]?.label || '--') }}
          </el-tag>

        </template>
        <template #actual="{ row }">
          {{ isNullOrEmpty(row.structInfo.map(item => `${item?.fieldName}=${row?.actual[item?.fieldAlias] ??
            null}`).join('、')) }}
        </template>
        <template #action="{ row }">
          <sj-link custom-type="sblue" :underline="false" @click="showDeviceInfo(row)">查看设备详情</sj-link>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig, haveRole } from '@/utils/functions'
import { ReNormalCountTo } from '@/components/ReCountTo/index'
import { getDeviceMonitoring, getDeviceMonitor } from "@/api/operate/application-system";
import { getAssetURL } from '@/utils/functions'
import { PAGE_LAYOUT } from "@/constant";
import { DEVICESTATUSTABLE, DEVICESTATUS } from '@/constant/device-mangenment'
import { debounce, deviceDetection } from '@pureadmin/utils';
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import { addDialog } from '@/components/ReDialog';
import deviceInfo from "@/views/operate/device-management/device-management/device-info.vue";
import { getInfo } from "@/api/operate/device-management/index";
import { message } from '@/utils/message';
const router = useRouter();
const props = defineProps({
  systemId: {
    type: String,
    default: null
  }
})
const headerTitle = {
  deviceCount: {
    name: '设备总数',
    value: 0,
  },
  normal: {
    name: '正常设备',
    value: 1
  },
  fault: {
    name: '故障设备',
    value: 3
  },
  offLine: {
    name: '离线设备',
    value: 2
  },
  alarm: {
    name: '报警设备',
    value: 4
  }
}
// offLine: '离线设备',
// alarm: '报警设备',
// }
const title = {
  id: '编号',
  unityName: '单位名称',
  projectName: '项目名称',
  deviceSN: '设备序列号',
  deviceId: '设备编号',
  place: '设备位置',
  productName: '产品类型',
  commStatus: '设备状态',
  actual: '实时数据',
  action: '操作'
}
const defaultSearchForm = () => {
  return {
    systematicId: props.systemId,
    deviceId: null,
    deviceSN: null,
    commStatus: null,
    page: 1,
    limit: 10
  }
}
const roleTableConfig = [
  { prop: "id", label: title.id, width: 60, align: "left", fixed: "left" },
  { prop: "unityName", label: title.unityName, minWidth: 150 },
  { prop: "projectName", label: title.projectName, minWidth: 150 },
  { slot: "deviceSN", label: title.deviceSN, minWidth: 100 },
  { prop: "place", label: title.place, minWidth: 150 },
  { prop: "productName", label: title.productName, minWidth: 100 },
  { slot: "commStatus", label: title.commStatus, minWidth: 100 },
  { slot: "actual", label: title.actual, minWidth: 200 },
  { slot: "action", label: title.action, width: 150 },
];
const searchFormRules = [
  {
    type: "input",
    field: "deviceSN",
    title: title.deviceSN,
    value: null,
    props: {
      type: 'input',
      placeholder: `请输入${title.deviceSN}`,
      clearable: true
    }
  },
  {
    type: "select",
    field: "commStatus",
    title: title.commStatus,
    value: null,
    options: DEVICESTATUS,
    props: {
      placeholder: `请选择${title.commStatus}`,
      clearable: true
    }
  },

  { type: "number", field: "systematicId", title: "systematicId", hidden: true },
  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
];
const key = ref(0)
const searchFrom = ref(defaultSearchForm())
const deviceOverviewData = ref(null)
const tableData = ref({
  data: [],
  total: 0
})
onMounted(() => {
  getDeviceMonitoring({ systematicId: props.systemId }).then(res => {
    deviceOverviewData.value = res.result
  })
  getTableList()
})

// 跳转页面
const goDevice = (item) => {
  if (item.value !== 0) {
    router.push(
      `/device-management/device-management?systematicId=${props.systemId}&commStatus=${item.value}`
    )
  } else {
    router.push(
      `/device-management/device-management?systematicId=${props.systemId}`
    )
  }

}
const getTableList = () => {
  // searchFrom.value.systematicId = props.systemId
  getDeviceMonitor(searchFrom.value).then(res => {
    tableData.value.data = res.result
    // tableData.value.total=res.result.total
  })
}
const formRef = ref();
const showDeviceInfo = row => {
  //
  if (!haveRole('business.device.select')) {
    message('您没有权限查看设备信息', { type: 'warning' })
    return
  }
  addDialog({
    title: `设备信息`,
    width: "1100px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      id: row.id
    },
    contentRenderer: () => h(deviceInfo, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        id: row.id,
        isLoading: true,
        newFormInline: null
      };
      getInfo({ id: row.id })
        .then(res => {
          if (res.code == 200) {
            options.props.newFormInline = res.result;
          }
        })
        .finally(() => {
          options.props.isLoading = false;
        });
    },
  });
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm());
  key.value++;
  getTableList();
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
</script>
<style lang="scss" scoped>
.equipment-overview {
  .equipment-overview-box {
    @apply w-full p-[16px] dark:bg-[var(--bg-2)] bg-[#fff] rounded-[4px];
  }
}
</style>
